using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Work.API.Applications.Write.Commands;
using Work.Domain;
using Work.ErrorCode;
using Work.Infrastructure.Interfaces;

namespace Work.API.Applications.Write.CommandHandlers
{
    /// <summary>
    /// 批量创建处方明细处理器
    /// </summary>
    public class CreatePrescriptionItemsCommandHandler : IRequestHandler<CreatePrescriptionItemsCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<PrescriptionItem> _prescriptionItemRepo;
        private readonly IBaseRepository<Appintment> _appointmentRepo;

        public CreatePrescriptionItemsCommandHandler(
            IBaseRepository<PrescriptionItem> prescriptionItemRepo,
            IBaseRepository<Appintment> appointmentRepo)
        {
            _prescriptionItemRepo = prescriptionItemRepo;
            _appointmentRepo = appointmentRepo;
        }

        public async Task<ApiResult<int>> Handle(CreatePrescriptionItemsCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                // 1. 验证预约是否存在
                var appointment = await _appointmentRepo.GetById(request.AppointmentId);
                if (appointment == null)
                {
                    result.Code = ApiEnum.失败;
                    result.Message = "预约不存在";
                    result.Data = 0;
                    return result;
                }

                // 2. 验证药品列表不为空
                if (request.Items == null || request.Items.Count == 0)
                {
                    result.Code = ApiEnum.失败;
                    result.Message = "药品列表不能为空";
                    result.Data = 0;
                    return result;
                }

                // 3. 创建处方明细列表
                var prescriptionItems = request.Items.Select(item => new PrescriptionItem
                {
                    AppointmentId = request.AppointmentId,
                    RecordId = request.RecordId,
                    PatientId = request.PatientId,
                    RegistrationNum = request.RegistrationNum ?? appointment.RegistrationNum,
                    MedicineName = item.MedicineName,
                    UnitPrice = item.UnitPrice,
                    Quantity = item.Quantity,
                    TotalAmount = item.UnitPrice * item.Quantity,
                    PaymentStatus = "未支付",
                    CreateTime = DateTime.Now,
                    CreateBy = request.CreateBy
                }).ToList();

                // 4. 批量添加
                var rows = await _prescriptionItemRepo.AddRange(prescriptionItems);

                if (rows > 0)
                {
                    result.Code = ApiEnum.成功;
                    result.Message = $"成功创建 {rows} 条处方明细";
                    result.Data = rows;
                }
                else
                {
                    result.Code = ApiEnum.失败;
                    result.Message = "处方明细创建失败";
                    result.Data = 0;
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.失败;
                result.Message = $"创建失败：{ex.Message}";
                result.Data = 0;
            }

            return result;
        }
    }
}

